package com.tong.cloud.redisson.idempotent.expression;

import com.tong.cloud.redisson.idempotent.annotation.Idempotent;
import com.tong.cloud.redisson.idempotent.exception.IdempotentException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.lang.reflect.Method;

public class ExpressResolver implements KeyResolver {
    private static final SpelExpressionParser PARSER = new SpelExpressionParser();

    private static final LocalVariableTableParameterNameDiscoverer DISCOVERER = new LocalVariableTableParameterNameDiscoverer();


    @Override
    public String resolver(Idempotent idempotent, JoinPoint point) {
        Object[] arguments = point.getArgs();
        String[] params = DISCOVERER.getParameterNames(getMethod(point));
        StandardEvaluationContext context = new StandardEvaluationContext();
        if(params!=null && params.length>0){
            for(int i=0;i<params.length;i++){
                context.setVariable(params[i],arguments[i]);
            }
        }
        Expression expression = PARSER.parseExpression(idempotent.key());
        return expression.getValue(context,String.class);
    }

    private Method getMethod(JoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        if (method.getDeclaringClass().isInterface()) {
            try {
                method = point.getTarget().getClass().getDeclaredMethod(point.getSignature().getName(), method.getParameterTypes());
            } catch (SecurityException | NoSuchMethodException e) {
                throw new IdempotentException(e);
            }
        }
        return method;
    }
}
